package com.wfl.sampling.web;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.wfl.sampling.aop.NoAuth;
import com.wfl.sampling.dao.ActivityDao;
import com.wfl.sampling.entity.Activity;
import com.wfl.sampling.entity.User;
import com.wfl.sampling.handler.PageUtil;
import com.wfl.sampling.service.ActivityService;
import com.wfl.sampling.service.UserParticipationService;
import com.wfl.sampling.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author gefangjie
 */
@RestController
@RequestMapping("/api/Activity")
public class ActivityController {
    @Autowired
    private UserParticipationService userParticipationService;
    @Autowired
    private ActivityService activityService;
    @Autowired
    private UserService userService;
    @ResponseBody
    @RequestMapping(value = "/order/orderManage", method = RequestMethod.POST)
    private  Map<String, Object> Activity(@RequestBody Activity activity)
            throws JsonParseException, JsonMappingException, IOException {
        Map<String, Object> modelMap = new HashMap<>();
        Activity ac = activity;
        System.out.println(activityService.findMaxId());
        System.out.println("后端接收到的活动信息是"+ac);
        Integer id = activityService.findMaxId();
        ac.setId(id);
        System.out.println("对接收到的活动设置Id值："+ac);
        boolean a = activityService.addActivity(ac);
        if(a){
            System.out.println("添加成功");
            modelMap.put("success", true);
            modelMap.put("message", "添加成功！");
            return modelMap;
        }
        else{
            System.out.println("添加失败");
            modelMap.put("success", false);
            modelMap.put("message", "添加失败！");
            return modelMap;
        }
    }
    @NoAuth
    //查询所有活动
    @GetMapping("/ListActivity")
    public ResponseEntity<Map<String, Object>> listActivity() {
        Map<String, Object> response = new HashMap<>();

        List<Map<String, Object>> activities = activityService.listAllActivity();
        // 直接将查询结果放入响应中，无论结果是否为空
        response.put("success", true);
        response.put("message", activities.isEmpty() ? "没有找到活动数据" : "获取成功！");
        response.put("activities", activities);

        return new ResponseEntity<>(response, HttpStatus.OK);
    }
    @NoAuth
    @PostMapping("/addactivity")
    public Map<String, Object> addactivity(@RequestBody Activity activity) {
        Map<String, Object> modelMap = new HashMap<>();
        Activity ac = activity;
        System.out.println("后端接收到的活动信息是"+ac);
        Integer id = activityService.findMaxId();
        System.out.println(id);
        ac.setId(id);
        System.out.println("对接收到的活动设置Id值："+ac);
        boolean a = activityService.addActivity(ac);
        if(a){
            System.out.println("添加成功");
            modelMap.put("success", true);
            modelMap.put("message", "添加成功！");
            return modelMap;
        }
        else{
            System.out.println("添加失败");
            modelMap.put("success", false);
            modelMap.put("message", "添加失败！");
            return modelMap;
        }
    }

    @RequestMapping("/admin/orderManage_{pageCurrent}_{pageSize}_{pageCount}")
    public String newsManage(Activity activity, @PathVariable Integer pageCurrent, @PathVariable Integer pageSize, @PathVariable Integer pageCount, Model model){
        //判断 页数
        if (pageSize == 0) pageSize = 10;
        if (pageCurrent == 0) pageCurrent = 1;

        int rows = activityService.countActivity(activity);
        if (pageCount == 0) pageCount = rows % pageSize == 0 ? (rows / pageSize) : (rows / pageSize) + 1;
        //查询
        activity.setStart((pageCurrent - 1) * pageSize);
        activity.setEnd(pageSize);
        List<Activity> activitys = activityService.findActivityByCondition(activity);
        //输出
        model.addAttribute("activitys", activitys);
        String pageHTML = PageUtil.getPageContent("orderManage_{pageCurrent}_{pageSize}_{pageCount}", pageCurrent, pageSize, pageCount);
        System.out.println(pageHTML);
        model.addAttribute("pageHTML", pageHTML);
        return "order/orderManage";
    }
    @RequestMapping(value = "/admin/orderDetail")
    private String orderDetail(Activity activity, Model model) {
        Integer activityId = activity.getId();
        List<Activity> activitys = activityService.findActivityByActivityId(activityId);
        model.addAttribute("activity", activitys);
        return "order/orderDetail";
    }
    @RequestMapping(value = "/admin/orderHandle")
    private String orderHandle(Activity activity, Model model) {
        Integer activityId = activity.getId();
        List<Activity> activitys = activityService.findActivityByActivityId(activityId);
        model.addAttribute("activity", activitys);
        return "order/orderHandle";
    }
    @PostMapping(value = "/join/activity")
    private ResponseEntity<String> addActivity(@RequestParam(name = "userId") Integer userId,
                                               @RequestParam(name = "activityId") Integer activityId) {
        userParticipationService.addParticipation(userId,activityId);
        return new ResponseEntity<>("参与成功！", HttpStatus.OK);
    }

    @PostMapping(value = "/listMyActivity")
    private ResponseEntity<List<Activity>> queryUpByUserId(@RequestParam(name = "userId") Integer userId) {
        List<Activity> activities = userParticipationService.queryUpByUserId(userId);
        System.out.println(activities);
        if (activities.isEmpty()) {
            return ResponseEntity.notFound().build();
            // 或者其他错误状态
        }
        return new ResponseEntity<>(activities, HttpStatus.OK);
    }

    //通过活动Id查询活动信息和发起人部分信息
    @GetMapping("/activityDetails/{activityId}")
    public ResponseEntity<Map<String, Object>> getActivityDetails(@PathVariable Integer activityId) {
        Map<String, Object> response = new HashMap<>();

        // 获取活动信息
        List<Activity> activities = activityService.findActivityByActivityId(activityId);
        if(activities.isEmpty()) {
            response.put("success", false);
            response.put("message", "活动未发现!");
            return new ResponseEntity<>(response, HttpStatus.NOT_FOUND);
        }

        Integer userId = Integer.valueOf(activities.get(0).getInitiatorId());
        User user = userService.getUserById(userId);
        if(user == null) {
            response.put("success", false);
            response.put("message", "组织者不存在!");
            return new ResponseEntity<>(response, HttpStatus.NOT_FOUND);
        }

        response.put("success", true);
        response.put("message", "获取活动详情成功!");
        response.put("activity", activities.get(0));
        response.put("organizer", user);

        return new ResponseEntity<>(response, HttpStatus.OK);
    }


}



 /* @RequestMapping(value = "/admin/orderHandle/modify", method = RequestMethod.GET)
    public ResponseEntity<Activity> modifyActivity(@RequestParam("examine") int examine,
                                            @RequestParam("remark") String remark,
                                            @RequestParam("id") int id) {
        try {
            List<Activity> activities = activityService.findActivityByActivityId(id);
            if (activities.isEmpty()) {
                return ResponseEntity.notFound().build(); // 或者其他错误状态
            }

            Activity ac = activities.get(0);
            ac.setRemark(remark);
            ac.setExamine(examine);

            boolean success = activityService.modifyActivityById(ac);

            if (success) {
                System.out.println("修改成功");
                return ResponseEntity.ok("修改成功");
            } else {
                System.out.println("修改失败");
                return ResponseEntity.badRequest().body("修改失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }*/

//返回新的ID
   /* @PostMapping(value = "/getActivityMaxID")
    public Map<String, Object> getMaxId()
            throws JsonParseException, JsonMappingException, IOException {
        System.out.println(" 新的ID值为： " + activityDao.findMaxId().get(0).getId() + 1);
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "登录成功！");
        response.put("MaxId",activityDao.findMaxId().get(0).getId() + 1);
        return response;
    }*/
    /*
    @RequestMapping(value = "/addActivity", method = RequestMethod.POST)
    private  Map<String, Object> addActivity(@RequestBody Activity activity)
            throws JsonParseException, JsonMappingException, IOException {
        Map<String, Object> response = new HashMap<>();
        int id  = activityDao.findMaxId().get(0).getId() + 1;
        activity.setId(id);
        System.out.println(" ActivityController addActivity : "+activity);
        boolean a = activityService.addActivity(activity);
        if(a){
            System.out.println("添加成功");
            response.put("success", true);
            response.put("message", "添加成功！");
            return response;
        }
        else{
            System.out.println("添加失败");
            response.put("success", false);
            response.put("message", "添加失败！");
            return response;
        }
    }*/